package cn.etynit.basic.aop;

import cn.etynit.basic.anno.LogAnno;
import cn.etynit.org.domain.Aop;
import cn.etynit.org.service.AopService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component//交给spring管理的注解
@Aspect
public class LogAop {

    @Autowired
    private AopService aopService;

    @Pointcut("@annotation(cn.etynit.basic.anno.LogAnno)")
    public void pointCut(){}


    @Around("pointCut()")
    public Object around(ProceedingJoinPoint pjp){
        // 获取到所有的方法，强转为MethodSignature
        MethodSignature signature = (MethodSignature) pjp.getSignature();
        // getMethod()获取到当前的方法
        Method method = signature.getMethod();
        // 获取到controller类方法的注解
        LogAnno annotation = method.getAnnotation(LogAnno.class);
        // 获取方法名称
        String method1 = annotation.method();
        System.out.println(method1);
        // 获取方法的描述
        String methodDes = annotation.methodDes();
        System.out.println(methodDes);
        // 创建日志管理类对象
        Aop aop = new Aop();
        // 添加获取到的方法及描述
        aop.setExecutionMethod(method1);
        aop.setMethodsDescribed(methodDes);
        // 调用方法添加到表
        aopService.add(aop);


        // 执行业务方法
        Object proceed = null;
        try {
            proceed = pjp.proceed();
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        // 添加日志
        return proceed;
    }

}
